package com.wise.config;

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.ServiceProperties;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType;
import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.wise.framework.exception.Excep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URISyntaxException;
import java.security.InvalidKeyException;

import static com.wise.model.content.ContentErrMsgs.Err_000100140020;

@Slf4j
@Configuration
public class AzureUploadConfig {

    @Value("${azure.defaultendpoints}")
    private String endpoints;

    @Value("${azure.accountname}")
    private String name;

    @Value("${azure.accountkey}")
    private String key;

    @Value("${azure.endpointsuffix}")
    private String suffix;

    @Bean
    public CloudBlobContainer cloudBlobContainer() {
        CloudBlobContainer cloudBlobContainer;
        try {
            String config = "DefaultEndpointsProtocol=" + endpoints + ";" + "AccountName=" + name
                    + ";" + "AccountKey=" + key + ";" + "EndpointSuffix=" + suffix;
            // 创建CloudStorageAccount对象
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(config);

            //创建 CloudBlobClient对象
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            //https://wisemedia.blob.core.chinacloudapi.cn/picture/TG-E%E5%BD%A9%E9%A1%B52020.pdf
            ServiceProperties serviceProperties = new ServiceProperties();
            serviceProperties.setDefaultServiceVersion("2013-08-15");
            blobClient.uploadServiceProperties(serviceProperties);
            // 创建容器，填入容器名，只能小写，大写则异常
            cloudBlobContainer = blobClient.getContainerReference("picture");

            //若容器名不存在，则新建
            cloudBlobContainer.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());

        } catch (URISyntaxException | InvalidKeyException | StorageException e) {
            log.error(e.getMessage(), e);
            throw Excep.le(Err_000100140020);
        }
        return cloudBlobContainer;
    }
}
